package dao

import (
	"go-web/db"
	"go-web/model"
	"gorm.io/gorm"
)

type UserDao struct {
	DB *gorm.DB
}

func NewUserDao() *UserDao {
	return &UserDao{DB: db.DB}
}

func (d *UserDao) Create(user *model.User) error {
	return d.DB.Create(user).Error
}

func (d *UserDao) GetByID(id uint) (*model.User, error) {
	var user model.User
	err := d.DB.First(&user, id).Error
	return &user, err
}

func (d *UserDao) GetByUsername(username string) (*model.User, error) {
	var user model.User
	err := d.DB.Where("username = ?", username).First(&user).Error
	return &user, err
}

func (d *UserDao) Update(user *model.User) error {
	return d.DB.Save(user).Error
}

func (d *UserDao) Delete(id uint) error {
	return d.DB.Delete(&model.User{}, id).Error
}

func (d *UserDao) List(page, pageSize int) ([]model.User, int64, error) {
	var users []model.User
	var count int64

	err := d.DB.Model(&model.User{}).Count(&count).Error
	if err != nil {
		return nil, 0, err
	}

	err = d.DB.Offset((page - 1) * pageSize).Limit(pageSize).Find(&users).Error
	return users, count, err
}
